package com.example.keshe0337.biz;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.keshe0337.dao.UserDao;
import com.example.keshe0337.database.AppDatabase;
import com.example.keshe0337.entity.User;
import com.example.keshe0337.utils.TimeConverters;

import java.util.Date;
import java.util.List;

public class UserService {

    private final UserDao userDao;

    public UserService(Context context) {
        AppDatabase db = AppDatabase.getInstance(context);
        this.userDao = db.userDao();
    }

    //注册
    public int register(User user) {
        User usersByPhone = userDao.findUsersByPhone(user.getPhone());
        if (usersByPhone != null) {
            return 1;//重复注册
        }
        if (user.getPhone().length()!=11) {
            return 2;//手机号格式错误
        }
        if (user.getPassword().length()<6) {
            return 3;//密码长度过短
        }
        user.setRegisterTime(TimeConverters.format(new Date()));
        user.setAge(0);
        user.setStatus(true);
        userDao.insertUser(user);
        return 0;//成功
    }

    //登陆
    public Long login(User user) {
        if (user.getPhone().equals("18237034291")) {
            if (user.getPassword().equals("123456")) {
                return -10L;
            }
            return -2L;
        }
        User usersByPhone = userDao.findUsersByPhone(user.getPhone());
        if (usersByPhone == null) {
            return -1L;//未注册
        }
        if (!usersByPhone.getPassword().equals(user.getPassword())) {
            Log.d("密码","原："+usersByPhone.getPassword()+";获："+user.getPassword());
            return -2L;//密码错误
        }
        return usersByPhone.getId();//成功
    }

    public int updateUser(User user) {
        if (user.getName() == null || user.getName().isBlank()) {
            return 1; //姓名字段无效
        }
        if (user.getAge() < 0 || user.getAge()>150) {
            return 2; // 年龄无效
        }

        userDao.updateUser(user);
        return 0;//成功
    }

    public User getUserById(Long id) {
        return userDao.getUserById(id);
    }

    public int cancel(User user) {
        User usersByPhone = userDao.findUsersByPhone(user.getPhone());
        if (usersByPhone == null) {
            return 1;//无效用户
        }
        userDao.deleteUser(usersByPhone);
        return 0;//成功
    }

}

